package com.jiangchao.mimidao.framework.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

public class FreemarkerParseFactory {

  private static final String ENCODE = "utf-8";
  /**
   * 文件缓存
   */
  private static final Configuration _tplConfig = new Configuration(Configuration.VERSION_2_3_28);
  /**
   * SQL 缓存
   */
  private static final Configuration _sqlConfig = new Configuration(Configuration.VERSION_2_3_28);

  private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();

  private FreemarkerParseFactory() {
  }


  // 使用内嵌的(?ms)打开单行和多行模式
  private final static Pattern p = Pattern
      .compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$");

  static {
    _tplConfig.setClassForTemplateLoading(
        new FreemarkerParseFactory().getClass(), "/");
    _tplConfig.setNumberFormat("0.#####################");
    _sqlConfig.setTemplateLoader(stringTemplateLoader);
    _sqlConfig.setNumberFormat("0.#####################");
    //classic_compatible设置，解决报空指针错误
    _sqlConfig.setClassicCompatible(true);
  }


  public static String parseTemplateContent(String templateSql, Map<String, Object> sqlParamsMap)
      throws IOException, TemplateException {
    StringWriter stringWriter = new StringWriter();
    if (stringTemplateLoader.findTemplateSource("sql_" + templateSql.hashCode()) == null) {
      stringTemplateLoader.putTemplate("sql_" + templateSql.hashCode(), templateSql);
    }
    Template template = _sqlConfig.getTemplate("sql_" + templateSql.hashCode(), ENCODE);
    template.process(sqlParamsMap, stringWriter);
    return getSqlText(stringWriter.toString());
  }

  private static String getSqlText(String sql) {
// 将注释替换成""
    sql = p.matcher(sql).replaceAll("");
    sql = sql.replaceAll("\\n", " ").replaceAll("\\t", " ")
        .replaceAll("\\s{1,}", " ").trim();
    // 去掉 最后是 where这样的问题
    if (sql.endsWith("where") || sql.endsWith("where ")) {
      sql = sql.substring(0, sql.lastIndexOf("where"));
    }
    // 去掉where and 这样的问题
    int index = 0;
    while ((index = StringUtils.indexOfIgnoreCase(sql, "where and", index)) != -1) {
      sql = sql.substring(0, index + 5)
          + sql.substring(index + 9, sql.length());
    }
    // 去掉 , where 这样的问题
    index = 0;
    while ((index = StringUtils.indexOfIgnoreCase(sql, ", where", index)) != -1) {
      sql = sql.substring(0, index)
          + sql.substring(index + 1, sql.length());
    }
    // 去掉 最后是 ,这样的问题
    if (sql.endsWith(",") || sql.endsWith(", ")) {
      sql = sql.substring(0, sql.lastIndexOf(","));
    }
    return sql;

  }


  public static boolean isExistTemplate(String sqlTempletPath) throws IOException {
    Template template = _tplConfig.getTemplate(sqlTempletPath);
    if (template == null) {
      return false;
    }
    return true;
  }

  public static String parseTemplate(String sqlTempletPath, Map<String, Object> sqlParamsMap)
      throws IOException, TemplateException {
    StringWriter swriter = new StringWriter();
    Template mytpl = _tplConfig.getTemplate(sqlTempletPath, ENCODE);
    mytpl.process(sqlParamsMap, swriter);
    return getSqlText(swriter.toString());
  }
}
